Trapping Rain Water

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.

For example,

Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.

Trapping Rain Water - 图1

The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.

Solution:

  1. public class Solution {
  2. public int trap(int[] height) {
  3. if (height == null || height.length == 0) {
  4. return 0;
  5. }
  6. int n = height.length;
  7. int max = 0;
  8. // scan from left
  9. int[] lmax = new int[n];
  10. for (int i = 0; i < n; i++) {
  11. lmax[i] = max;
  12. max = Math.max(max, height[i]);
  13. }
  14. // scan from right
  15. max = 0;
  16. int[] rmax = new int[n];
  17. for (int i = n - 1; i >= 0; i--) {
  18. rmax[i] = max;
  19. max = Math.max(max, height[i]);
  20. }
  21. // final scan
  22. int res = 0;
  23. for (int i = 0; i < n; i++) {
  24. int water = Math.min(lmax[i], rmax[i]) - height[i];
  25. res += water >= 0 ? water : 0;
  26. }
  27. return res;
  28. }
  29. }